package com.jn.gsondemo.views;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import com.jn.gsondemo.R;

import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class MedalCountActivity extends Activity {
    private TextView goldTextView;
    private TextView silverTextView;
    private TextView bronzeTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_medal_count);

        // 初始化UI元素
        goldTextView = findViewById(R.id.goldTextView);
        silverTextView = findViewById(R.id.silverTextView);
        bronzeTextView = findViewById(R.id.bronzeTextView);

        // 解析JSON数据
        parseJson();
    }

    private void parseJson() {
        // 读取assets文件夹中的olympic.json文件
        String json = readJsonFromAsset("olympic.json");
        try {
            JSONObject olympicObject = new JSONObject(json);
            JSONArray countriesArray = olympicObject.getJSONArray("countries");

            for (int i = 0; i < countriesArray.length(); i++) {
                JSONObject countryObject = countriesArray.getJSONObject(i);
                String countryName = countryObject.getString("name");
                int gold = countryObject.getInt("gold");
                int silver = countryObject.getInt("silver");
                int bronze = countryObject.getInt("bronze");

                // 将数据设置到UI元素上
                goldTextView.setText("Gold: " + gold);
                silverTextView.setText("Silver: " + silver);
                bronzeTextView.setText("Bronze: " + bronze);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String readJsonFromAsset(String fileName) {
        StringBuilder builder = new StringBuilder();
        try {
            InputStream is = getAssets().open(fileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return builder.toString();
    }
}